package com.cs410.collabwriting.servlets;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;

import com.cs410.collabwriting.connectors.SessionManager;
import com.cs410.collabwriting.main.User;
import com.cs410.collabwriting.main.UserManager;
import com.cs410.collabwriting.tools.LogManager;


import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Servlet implementation class LoginManager
 */
@WebServlet("/login")
public class LoginManager extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginManager() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userID = request.getParameter("user");
		String password = request.getParameter("password");
		String action = request.getParameter("action");
		
		JSONObject json = new JSONObject();
		if( action != null ) {
			try {
				if( action.compareToIgnoreCase("logout") == 0) {
					json.put("loggedOut", "true");
					SessionManager.removeJSessionUserIDPair( request.getRequestedSessionId() );
				} else if( action.compareToIgnoreCase("login") == 0 ) {
					if( userID == null || password == null || userID.isEmpty() || password.isEmpty() ) {
						json.put("loggedIn", "false");
						json.put("reason", "Username and Password cannot be empty!");
					} else {
						User user = UserManager.login( userID , password );
						if( user != null ) {
							json.put("loggedIn", "true");
							SessionManager.addJSessionUserIDPair( request.getRequestedSessionId(), user );
						} else {
							LogManager.logWarning("[LoginManager] -- Invalid Credentials received for Username <" + userID + ">" );
							json.put("loggedIn", "false");
							json.put("reason", "Invalid Credentials, Please enter a valid Username and Password!");
						}
					}	
				} else if( action.compareToIgnoreCase("forgotpassword") == 0 ) {
					if( userID != null && !userID.isEmpty() ) {
						User user = UserManager.getInstance().getUser( userID );
						if( user != null ) {
							try {
								SendEmailToUser( user );
								json.put("error","false");
								json.put("reason","Please check your email!");
							} catch (Exception e) {
								LogManager.logError("[LoginManager] --  " + e.getMessage() );
							}
						} else {
							json.put("error","true");
							json.put("reason","user does not exist");
						}
					} else {
						json.put("error","true");
						json.put("reason","invalid userid");
					}
				}
			} catch (JSONException e) {
			
			}
		}
		response.getWriter().print( json.toString() );
	}

	/*
	 * JAVA MAIL CODE ADAPTED FROM :
	 * http://www.java2s.com/Code/Java/Network-Protocol/SendmailusingGMAIL.htm
	 */
	private void SendEmailToUser(User user) throws Exception {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.auth", "true");
		props.put("mail.debig","true");
		props.put("mail.smtp.port", "465" );
		props.put("mail.smtp.socketFactory.port","465");
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback","false");
		
		Session session = Session.getDefaultInstance( props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("cs410writeon","ubccpsc410");
			}
		});
		session.setDebug( true );
		Message message = new MimeMessage(session);
		InternetAddress from = new InternetAddress("cs410writeon@gmail.com");
		message.setFrom( from );
		InternetAddress addressTo = new InternetAddress( user.getEmailAddress() );
		message.setRecipient( Message.RecipientType.TO, addressTo );
		message.setSubject("Forgotten Password Request for " + user.getUserID());
		String text = "You requested a password for user: " + user.getUserID()
				+ ". Your password is: " + user.getPassword() + ".";
		message.setContent(text, "text/html");
		Transport.send( message );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
